package org.wu.framework.lazy.database.datasource.proxy.handler;

import org.wu.framework.core.Ordered;
import org.wu.framework.core.exception.AssertFactory;
import org.wu.framework.lazy.database.datasource.proxy.audit.LazyAuditAdapter;

import java.util.Comparator;
import java.util.List;

/**
 * 数据源适配器
 */
public class JdbcHandlerAdapter {

    // datasource 处理器
    private final List<DataSourceHandler> dataSourceHandlerList;
    // connection 连接处理器
    private final List<ConnectionHandler> connectionHandlerList;

    // sql 审计处理器
    private final LazyAuditAdapter lazyAuditAdapter;

    public JdbcHandlerAdapter() {
        this.dataSourceHandlerList = List.of(new LazyDataSourceHandler());
        this.connectionHandlerList = List.of(new LazyConnectionHandler());
        this.lazyAuditAdapter = null;
    }

    public JdbcHandlerAdapter(List<DataSourceHandler> dataSourceHandlerList, List<ConnectionHandler> connectionHandlerList, LazyAuditAdapter lazyAuditAdapter) {
        this.dataSourceHandlerList = dataSourceHandlerList;
        this.connectionHandlerList = connectionHandlerList;
        this.lazyAuditAdapter = lazyAuditAdapter;
    }


    public DataSourceHandler findFirstDataSourceHandler() {
        AssertFactory.notNull(dataSourceHandlerList,"数据源处理器不能为空");
        return dataSourceHandlerList.stream().sorted(Comparator.comparing(Ordered::getOrder)).findFirst().get();
    }

    public ConnectionHandler findFirstConnectionHandler() {
        AssertFactory.notNull(connectionHandlerList,"数据库连接处理器不能为空");
        return connectionHandlerList.stream().sorted(Comparator.comparing(Ordered::getOrder)).findFirst().get();
    }

    public LazyAuditAdapter findLazyAuditAdapter() {
        return lazyAuditAdapter;
    }
}
